layui.use(['jquery', 'common', 'tree'], () => {
    var $ = layui.jquery, tree = layui.tree;
    window.tree = {
        selectChecked: (id, data, checkedIds) => {
            var hasId = (ids, id) => {
                for (var i = 0; i < ids.length; i++) {
                    if (ids[i] == id) {
                        return true;
                    }
                }
                
                return false;
            };
            
            if (checkedIds.length == 0) return;
            for (var i = 0; i < data.length; i++){
                if (data[i].children && data[i].children.length > 0){
                    window.tree.selectChecked(id, data[i].children, checkedIds); // 支节点则递归所有子项
                } else if (hasId(checkedIds, data[i].id)) {
                    tree.setChecked(id, data[i].id); // 叶子节点才选择
                }
            }
        }
        , getCheckedIds : (id) => {
            var checkedTreeIds = [];
            window.tree.getCheckedChildren(tree.getChecked(id), checkedTreeIds);
            return checkedTreeIds;
        }
        , getCheckedChildren: (data, checkedTreeIds) => {
            for(var i = 0; i < data.length; i++){
                checkedTreeIds.push(data[i].id);
                if (data[i].children && data[i].children.length > 0) {
                    window.tree.getCheckedChildren(data[i].children, checkedTreeIds);
                }
            }
        }
    }
});